#!/bin/bash

dl_path='/dl/redis'
install_path='/basic/redis'

dep_install() {
  yum install -y gcc
}

dl_unzip() {
  mkdir -p $dl_path
  cd $dl_path || exit
  local tarFile
  tarFile='redis-6.2.6.tar.gz'
  wget -O $tarFile http://download.redis.io/releases/redis-6.2.6.tar.gz

  if [ -e $tarFile ]; then
    tar -zxvf $tarFile
    rm -rf $tarFile
    dl_dir='/dl/redis/redis-6.2.6'
  else
    echo '下载安装包失败！'
    exit
  fi
}

install() {
  cd $dl_dir || exit
  make
  make install PREFIX=$install_path
  #备份配置文件
  cp $dl_dir/redis.conf $install_path/bin/backup.conf
  rm -rf $dl_path
}
#TODO:存在隐患，直接新瓶装旧酒的话万一配置文件版本不兼容咋办。所以还得狂草
edit_conf() {
  cp $install_path/bin/backup.conf $install_path/bin/redis.conf
  local file=$install_path/bin/redis.conf
  local line1
  local line2
  local line3
  local line4
  local line5
  local line6

  -n表示不输出，-r表示
  /=表示显示匹配到的行的行号，/p显示匹配到的行本身

  line1=$(sed -nr '/^bind 127.0.0.1/=' $file)
  sed -i "${line1}c # bind 127.0.0.1" $file

  line2=$(sed -nr '/^protected-mode /=' $file)
  sed -i "${line2}c protected-mode no" $file

  line3=$(sed -nr '/^timeout /=' $file)
  sed -i "${line3}c timeout 120" $file

  line4=$(sed -nr '/^daemonize /=' $file)
  sed -i "${line4}c daemonize no" $file

  line5=$(sed -nr '/^# requirepass /=' $file)
  sed -i "${line5}c requirepass wstx6379" $file

  line6=$(sed -nr '/^appendonly /=' $file)
  sed -i "${line6}c appendonly yes" $file

  #启动
  cd $install_path/bin || exit
  nohup ./redis-server redis.conf &
}

open_port() {
  firewall-cmd --zone=public --add-port=6379/tcp --permanent
  firewall-cmd --reload
}

dep_install
dl_unzip
install
edit_conf
open_port